using System.Collections.Generic;
using ProtoModels;

public class LeaderboardPositionInfoManager : BehaviourSingletonInit<LeaderboardPositionInfoManager>
{
	public delegate void OnGetPlayerPositionComplete(PlayerPositions.PlayerPosition playerPosition);

	public List<PlayerPositions.PlayerPosition> playerPositions = new List<PlayerPositions.PlayerPosition>();

	public override void Init()
	{
		ClearPlayerCache();
	}

	public void ClearPlayerCache()
	{
		playerPositions.Clear();
	}

	public void GetPlayerPostion(string pid, OnGetPlayerPositionComplete onComplete)
	{
		PlayerPositions.PlayerPosition playerPosition = TryGetPlayerFromCachedList(pid);
		if (playerPosition != null)
		{
			if (onComplete != null)
			{
				onComplete(playerPosition);
			}
			return;
		}
		GGServerRequestsBackend.GetPlayerPositionsRequest getPlayerPositionsRequest = new GGServerRequestsBackend.GetPlayerPositionsRequest();
		PlayerPositions playerPositions = new PlayerPositions();
		PlayerPositions.PlayerPosition playerPosition2 = new PlayerPositions.PlayerPosition();
		playerPosition2.playerId = pid;
		playerPositions.players.Add(playerPosition2);
		getPlayerPositionsRequest.AddData(playerPositions);
		BehaviourSingletonInit<GGServerRequestsBackend>.instance.GetPlayerPositionList(getPlayerPositionsRequest, delegate(GGServerRequestsBackend.ServerRequest request)
		{
			if (request.status != 0)
			{
				if (onComplete != null)
				{
					onComplete(null);
				}
			}
			else
			{
				PlayerPositions response = request.GetResponse<PlayerPositions>();
				PlayerPositions.PlayerPosition playerPosition3 = ((response.players.Count <= 0) ? null : response.players[0]);
				AddPlayerPositionFromExternalSource(playerPosition3);
				if (onComplete != null)
				{
					onComplete(playerPosition3);
				}
			}
		});
	}

	public PlayerPositions.PlayerPosition TryGetPlayerFromCachedList(string pid)
	{
		foreach (PlayerPositions.PlayerPosition playerPosition in playerPositions)
		{
			if (playerPosition.playerId == pid)
			{
				return playerPosition;
			}
		}
		return null;
	}

	public void AddPlayerPositionFromExternalSource(PlayerPositions.PlayerPosition playerPosition)
	{
		if (playerPosition != null)
		{
			PlayerPositions.PlayerPosition playerPosition2 = TryGetPlayerFromCachedList(playerPosition.playerId);
			if (playerPosition2 != null)
			{
				playerPositions.Remove(playerPosition2);
			}
			playerPositions.Add(playerPosition);
		}
	}
}
